﻿using System;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Newtonsoft.Json.Linq;
using Quartz;
using Quartz.Impl.AdoJobStore.Common;
using QW.Core.AutoTasks;
using QW.Found.AutoTasks;

namespace QW.Found.TasksTasks.Quartz
{
    /// <summary>
    /// 
    /// </summary>
    public class TaskJob : IJob
    {
        private readonly ILogger logger;
        /// <summary>
        /// .ctor
        /// </summary>
        /// <param name="factory"></param>
        public TaskJob(ILoggerFactory factory)
        {
            this.logger = factory.CreateLogger("taskCenter");
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public Task Execute(IJobExecutionContext context)
        {
            var detail = context.MergedJobDataMap["TaskDescriptor"] as TaskDescriptor<JobKey>;
            try
            {
                detail.Handler.Invoke(detail.Instance, null);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"任务中心未处理异常:{detail.Name}");
            }
            return Task.CompletedTask;
        }
    }
}
